package research.ui.editors;

import java.util.Calendar;

import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import research.dao.hibernate.HibernateUtil;
import research.domain.Application;
import research.domain.Calander;
import research.domain.FilmType;
import research.entity.EntityType;
import research.model.EntityListContentProvider;
import research.model.ListHierarchy;
import research.persistence.PersistenceManager;
import research.ui.editors.input.EntityEditorInput;

public class ApplicationEditor extends FormEntityEditor {
	public static String ID = "research.ui.editors.ApplicationEditor";
	private Text registration_number;
	private Text task;
	private DateTime date;
	private DateTime desdate;
	private Text documents;
	private Text desied_results;
	private Text company_name;
	private Text declarant_name;
	private Text specialist_name;
	private ComboViewer calander;
	private ComboViewer filmType;

	private Application getEntity() {
		return (Application) entity;
	}

	@Override
	protected boolean checkInputEntityType(EntityEditorInput input) {
		return input.getEntity().getType().equals(EntityType.Application);
	}
	
	private void checkRegNumber() {
		if (this.getEntity().getRegistration_number() == null || this.getEntity().getRegistration_number().isEmpty()) {
			Session s = HibernateUtil.getSessionFactory().getCurrentSession();
			String num = null;
			try {
				s.beginTransaction();
				num = (String) s.getNamedQuery("ApplicationGetNextRegNumber").uniqueResult();
				s.getTransaction().commit();
			} catch (HibernateException e) {
				s.getTransaction().rollback();
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
			
			if (num != null && !num.isEmpty())
				num = String.valueOf(Integer.parseInt(num) + 1);
			else 
				num = "1";
			this.getEntity().setRegistration_number(num);
		}
	}

	@Override
	protected void fill() {
		checkRegNumber();
		
		this.task.setText(this.getEntity().getTask());
		this.documents.setText(this.getEntity().getDocuments());
		this.desied_results.setText(this.getEntity().getDesired_results());
		this.company_name.setText(this.getEntity().getCompany_name());
		this.declarant_name.setText(this.getEntity().getDeclarant_name());
		this.specialist_name.setText(this.getEntity().getSpecialist_name());
		this.registration_number.setText(this.getEntity().getRegistration_number());
		
		Calendar newdate = Calendar.getInstance();
		newdate.setTime(this.getEntity().getDate());
		int year = newdate.get(Calendar.YEAR);
		int month = newdate.get(Calendar.MONTH);
		int day = newdate.get(Calendar.DAY_OF_MONTH);
		date.setYear(year);
		date.setMonth(month);
		date.setDay(day);
		
		newdate = Calendar.getInstance();
		newdate.setTime(this.getEntity().getDesired_date());
		year = newdate.get(Calendar.YEAR);
		month = newdate.get(Calendar.MONTH);
		day = newdate.get(Calendar.DAY_OF_MONTH);
		desdate.setYear(year);
		desdate.setMonth(month);
		desdate.setDay(day);
		
		setComboEntity(calander, this.getEntity().getCalander());
		
		setComboEntity(filmType, this.getEntity().getFilmType());
		
	}

	@Override
	protected void initialize() {
	}

	@Override
	protected boolean readAndValidate() {
		this.getEntity().setCompany_name(this.company_name.getText());
		this.getEntity().setDeclarant_name(this.declarant_name.getText());
		this.getEntity().setDesired_results(this.desied_results.getText());
		this.getEntity().setDocuments(this.documents.getText());
		this.getEntity().setRegistration_number(this.registration_number.getText());
		this.getEntity().setSpecialist_name(this.specialist_name.getText());
		this.getEntity().setTask(this.task.getText());

		Calendar date = Calendar.getInstance();
		date.set(this.date.getYear(), this.date.getMonth(), this.date.getDay(),
				0, 0, 0);
		this.getEntity().setDate(date.getTime());
		
		date.set(this.desdate.getYear(), this.desdate.getMonth(), this.desdate.getDay(),
				this.desdate.getHours(), this.desdate.getMinutes(), this.desdate
						.getSeconds());
		this.getEntity().setDesired_date(date.getTime());
		
		Calander cal = (Calander) getComboEntity(calander);
		FilmType type = (FilmType) getComboEntity(filmType);
		
		this.getEntity().setCalander(cal);
		this.getEntity().setFilmType(type);

		return validateText(desied_results) && validateText(declarant_name) && validateText(registration_number);
	}

	@Override
	protected void renderForm() {
		TableWrapData td;
		Label label;
		Section section;
		Composite composite;
		GridData gd;
		
		/*
		 * Registration number
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Регистрационный номер*");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		registration_number = toolkit.createText(composite, "",
				SWT.BORDER);
		gd.widthHint = 100;
		registration_number.setLayoutData(gd);
		registration_number.addModifyListener(getTextModifyListener());

		/*
		 * Task
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Описание задания");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		task = toolkit.createText(composite, "",
				SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
		gd.widthHint = 200;
		gd.heightHint = 60;
		task.setLayoutData(gd);
		task.addModifyListener(getTextModifyListener());
		
		/*
		 * Calander
		 */		
		gd = new GridData();
		label = toolkit.createLabel(composite, "Каландровая линия:");
		label.setLayoutData(gd);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		calander = new ComboViewer(composite, SWT.DROP_DOWN
				| SWT.READ_ONLY);
		calander.setContentProvider(new EntityListContentProvider(new ListHierarchy(EntityType.Calander), true));
		calander.setLabelProvider(new LabelProvider());
		calander.setInput(PersistenceManager.getInstance());
		gd.widthHint = 100;
		calander.getCombo().setLayoutData(gd);
		calander.getCombo().addModifyListener(getTextModifyListener());
		
		/*
		 * Film Type
		 */
		gd = new GridData();
		label = toolkit.createLabel(composite, "Тип пленки:");
		label.setLayoutData(gd);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		filmType = new ComboViewer(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
		filmType.setContentProvider(new EntityListContentProvider(new ListHierarchy(EntityType.FilmType), true));
		filmType.setLabelProvider(new LabelProvider());
		filmType.setInput(PersistenceManager.getInstance());
		gd.widthHint = 100;
		filmType.getCombo().setLayoutData(gd);
		filmType.getCombo().addModifyListener(getTextModifyListener());
		
		/*
		 * Date
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Дата");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(2, false));
		section.setClient(composite);
		gd = new GridData();
		label = toolkit.createLabel(composite, "Дата составления*:");
		label.setLayoutData(gd);
		gd = new GridData();
		date = new DateTime(composite, SWT.DATE);
		date.setLayoutData(gd);

		/*
		 * Desired date
		 */
		gd = new GridData();
		label = toolkit.createLabel(composite, "Дата проведения:");
		label.setLayoutData(gd);
		gd = new GridData();
		desdate = new DateTime(composite, SWT.DATE);
		desdate.setLayoutData(gd);
		
		/*
		 * Documents
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		section.setLayoutData(td);
		section.setText("Перечень прилагаемых к заданию документов и материалов");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		documents = toolkit.createText(composite, "",
				SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
		gd.widthHint = 200;
		gd.heightHint = 60;
		documents.setLayoutData(gd);
		documents.addModifyListener(getTextModifyListener());
		
		/*
		 * Results
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Результаты работы, которые необходимо предоставить*");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		desied_results = toolkit.createText(composite, "",
				SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
		gd.widthHint = 200;
		gd.heightHint = 60;
		desied_results.setLayoutData(gd);
		desied_results.addModifyListener(getTextModifyListener());
		
		/*
		 * Company
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Компания-закачик");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		company_name = toolkit.createText(composite, "",
				SWT.BORDER);
		gd.widthHint = 100;
		company_name.setLayoutData(gd);
		company_name.addModifyListener(getTextModifyListener());
		
		/*
		 * Declarant
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("ФИО заявителя*");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		declarant_name = toolkit.createText(composite, "",
				SWT.BORDER);
		gd.widthHint = 100;
		declarant_name.setLayoutData(gd);
		declarant_name.addModifyListener(getTextModifyListener());
		
		/*
		 * Specialist
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("ФИО специалиста");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		specialist_name = toolkit.createText(composite, "",
				SWT.BORDER);
		gd.widthHint = 100;
		specialist_name.setLayoutData(gd);
		specialist_name.addModifyListener(getTextModifyListener());

	}

}
